package com.xaicode.learn.netty.tcpStickyAndUnpacking;

import cn.hutool.core.util.RandomUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 9:55
 */
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private AtomicInteger count = new AtomicInteger(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // send 10 msg
        for (int i = 1; i < 11; i++) {
            int strLength = RandomUtil.randomInt(100, 200);
            ByteBuf byteBuf = Unpooled.copiedBuffer(
                    String.format("\nnumber %d - msg: %s", i, "hello server"),
                    CharsetUtil.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        // read client msg
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String receivedServerMsg = new String(buffer, StandardCharsets.UTF_8);

        log.info("receive count [{}] msg: {}", count.incrementAndGet(), receivedServerMsg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
